package com.example.app.init.redis;

import com.example.app.utils.AesUtil;
import lombok.Getter;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

@Component
public class RedissonConfig implements InitializingBean {
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private int database;

    @Value("${spring.redis.timeout}")
    private int timeout;

    private final AesUtil aesUtil;

    @Getter
    private RedissonClient redissonClient;

    public RedissonConfig(AesUtil aesUtil) {
        this.aesUtil = aesUtil;
    }

    @Override
    public void afterPropertiesSet() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + aesUtil.decrypt(host) + ":" + port)
                .setDatabase(database)
                .setPassword(aesUtil.decrypt(password))
                .setTimeout(timeout);
        this.redissonClient = Redisson.create(config);
    }

    @Bean
    public RedissonClient redissonClient(RedissonConfig holder) {
        return holder.getRedissonClient();
    }
    @PreDestroy
    public void shutdown() {
        if (redissonClient != null) {
            redissonClient.shutdown();
        }
    }
}
